import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {RoleInfoService} from "../service/role-info.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {ActivatedRoute} from "@angular/router";

@Component({
  selector: 'app-role-edit',
  templateUrl: './role-edit.component.html',
  styleUrls: ['./role-edit.component.less']
})
export class RoleEditComponent implements OnInit {

  remarkMaxLength = 1000

  validateForm = new FormGroup({
    roleName: new FormControl(null, [Validators.required, Validators.maxLength(20)]),
    remark: new FormControl(null, [Validators.maxLength(this.remarkMaxLength)]),
    pid: new FormControl(null)
  })

  loading = false

  constructor(private roleService: RoleInfoService, private msg: NzMessageService,private routeInfo:ActivatedRoute) {
  }

  ngOnInit(): void {
    const pid = this.routeInfo.snapshot.queryParams["pid"];
    if (pid) {
      this.loading = true
      this.roleService.getById(pid).subscribe(value => {
        if (value) {
          this.validateForm.patchValue(value);
        }
      }, () => this.loading = false, () => this.loading = false)
    }
  }

  get pid() {
    return this.validateForm.get("pid").value
  }

  submitForm() {
    if (this.validateForm.valid) {
      const role = this.validateForm.getRawValue();
      this.loading = true
      this.roleService.save(role).subscribe(value => {
        this.loading = false
        this.validateForm.patchValue(value);
        this.msg.success("保存成功")
      }, () => this.loading = false)
    } else {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }
  }

}
